package com.baizhi.service.impl;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.mapper.CmfzAdminDAO;
import com.baizhi.service.CmfzAdminService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class CmfzAdminServiceImpl implements CmfzAdminService {
    @Autowired
    private CmfzAdminDAO cmfzAdminDAO;

    @Override
    public Page<CmfzAdmin> selectAll(Integer page, Integer limit) {
        //selectPage 两个参数 一个分页，一个条件
        Page<CmfzAdmin> adminPage =
                cmfzAdminDAO.selectPage(new Page<CmfzAdmin>(page, limit),null);
        return adminPage;
    }
    @Override
    public int insert(CmfzAdmin admin) {
        int insert = cmfzAdminDAO.insert(admin);
        return insert;
    }

    @Override
    public CmfzAdmin selectOneByUserName(String username) {
        CmfzAdmin cmfzAdmin = cmfzAdminDAO.selectOne(new QueryWrapper<CmfzAdmin>().eq("username",username));
        return cmfzAdmin;
    }

    @Override
    public Boolean register(String username, String password) {
        System.out.println("业务层username："+username);
        System.out.println("业务层password:"+password);
        CmfzAdmin cmfzAdmin = cmfzAdminDAO.selectOne(new QueryWrapper<CmfzAdmin>().eq("username",username));
        /*如果注册的用户名已经存在则不允许注册*/
        if (cmfzAdmin != null){
            return false;
        }else {
            /*1.随机获取盐值*/
            String salt = UUID.randomUUID().toString().substring(0, 4);
            System.out.println("随机盐值："+salt);
            /*2.根据shiro加密工具类 对明文密码进行加密处理
            * 加盐 加散列
            * */
            Md5Hash hash = new Md5Hash(password, salt, 1024);
            /*获取加密后的密文*/
            String s = hash.toHex();
            System.out.println("密文："+s);
            CmfzAdmin admin = new CmfzAdmin(null,username,s,salt);
           /* cmfzAdmin.setUsername(username);
            cmfzAdmin.setPassword(s);
            cmfzAdmin.setSalt(salt);*/
            System.out.println("要添加的管理员:"+cmfzAdmin);
            /*添加到数据库*/
            cmfzAdminDAO.insert(admin);
            return true;
        }
    }
}
